package com.broadsoft.platform.wfengine.runtime.nodehandler;

import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broadsoft.platform.wfengine.NodeType;
import com.broadsoft.platform.wfengine.parser.ParsedWorkflowDefinition;
import com.broadsoft.platform.wfengine.runtime.WfContext;
import com.broadsoft.platform.wfengine.runtime.WfEngine;
import com.broadsoft.platform.wfengine.runtime.impl.NodeExecutionServiceImpl;
import com.broadsoft.platform.wfengine.runtime.impl.SplitRunnable;

public class SplitNodeExecutionHandler implements INodeExecutionHandler {

    private final static Logger logger = LoggerFactory.getLogger(NodeExecutionServiceImpl.class);

    public SplitNodeExecutionHandler(ParsedWorkflowDefinition parsedWorkflowInfo,WfEngine wfEngine){
        this.parsedWorkflowInfo=parsedWorkflowInfo; 
        this.wfEngine=wfEngine;
        
    }
    
    @Override
    public NodeType executeNode(NodeType currentNode, WfContext flowContext) {
        if (logger.isTraceEnabled()) {
            logger.trace("The method[executeSplitNode] begin");
        }
        flowContext.setPreviousNode(currentNode);
        List<String> listOfDestNodeName = currentNode.getDestNode();

        if (logger.isTraceEnabled()) {
            logger.trace("The variable[wfEngine] is {}.",wfEngine);
        }
        for (String destNodeName : listOfDestNodeName) {
            WfContext subFlowContext=new WfContext(flowContext);
            subFlowContext.setWorkflowType(flowContext.getWorkflowType());
            subFlowContext.setPreviousNode(currentNode);
            NodeType nodeType = parsedWorkflowInfo
                    .getNodeTypeByName(flowContext.getWorkflowType().getName(), destNodeName);
            SplitRunnable splitRunnable = new SplitRunnable(nodeType, subFlowContext, wfEngine);
            executor.execute(splitRunnable); 
        }//end of for

        if (logger.isTraceEnabled()) {
            logger.trace("The method[executeSplitNode] end");
        }
        return null;
    }

    private ParsedWorkflowDefinition parsedWorkflowInfo;

    public ParsedWorkflowDefinition getParsedWorkflowInfo() {
        return parsedWorkflowInfo;
    }

    public void setParsedWorkflowInfo(ParsedWorkflowDefinition parsedWorkflowInfo) {
        this.parsedWorkflowInfo = parsedWorkflowInfo;
    }

    private final Executor executor = Executors.newFixedThreadPool(10);
    

    private WfEngine wfEngine;

    public WfEngine getWfEngine() {
        return wfEngine;
    }

    public void setWfEngine(WfEngine wfEngine) {
        this.wfEngine = wfEngine;
    }
    
    
}
